﻿using System;
using System.Collections.Generic;
using System.Linq;
using VideoSeller.Business.Data;
using VideoSeller.Core.Interfaces;

namespace VideoSeller.Business.Models
{
    public class OnlineContentClaimModel : Repository<OnlineContentClaim>
    {
        private readonly IDatabaseSettingsProvider _databaseSettingsProvider;
        public OnlineContentClaimModel(IDatabaseSettingsProvider databaseSettingsProvider)
		{
			_databaseSettingsProvider = databaseSettingsProvider;
		}
        public int GetClaimsContentCount(int onlineContentId)
        {
             return   Table.Where(x => x.OnlineContentId == onlineContentId).Count();
        }
        public int GetClaimsUserCount(Guid UserId)
        {
            return Table.Where(x => x.UserId == UserId).Count();
        }

		public bool HasUserContentClaimsForLastTime(Guid userId, DateTime startDate)
		{
			if (startDate == DateTime.MinValue)
			{
				return false;
			}

			return (from content in DataContext.OnlineContents
					join claim in Table on content.Id equals claim.OnlineContentId
					where content.UserId == userId && claim.Date >= startDate
					select claim).Any();
		}

        public void DeleteClaimsContent(int onlineContentId)
        {
            Table.DeleteAllOnSubmit(Table.Where(x => x.OnlineContentId == onlineContentId).AsEnumerable());
            SubmitAllChanges();
        }
        public void DeleteClaimsUser(Guid UserId)
        {
            Table.DeleteAllOnSubmit(Table.Where(x => x.UserId == UserId).AsEnumerable());
            SubmitAllChanges();
        }
        public void DeleteAll(IEnumerable<OnlineContentClaim> items)
        {
			foreach (var item in items)
			{
				var claim = Table.SingleOrDefault(x => x.Id == item.Id);

				if (claim != null)
				{
					Table.DeleteOnSubmit(claim);
				}
			}

			SubmitAllChanges();
        }
        public int SetClimeFromUser(int onlineContentId, String UserId)
        {
            Guid userId = new Guid(UserId);
            IEnumerable<OnlineContentClaim> uc = Table.Where(x => x.OnlineContentId == onlineContentId);
            int cnt = uc.Count();
            if (cnt > 0 && uc.Where(x => x.UserId == userId).Count() > 0)
                return cnt;
            OnlineContentClaim c = new OnlineContentClaim();
            c.OnlineContentId = onlineContentId;
            c.UserId = userId;
	        c.Date = DateTime.Now;
            Table.InsertOnSubmit(c);
            SubmitAllChanges();
            return cnt + 1;

        }
    }
}
